import { createSlice, nanoid, PayloadAction } from '@reduxjs/toolkit'

export type TodoItemType = {
  id: string
  title: string
  completed: boolean
}

const INIT_STATE: TodoItemType[] = [
  {
    id: nanoid(5),
    title: '吃饭',
    completed: false,
  },
  {
    id: nanoid(5),
    title: '吃饭',
    completed: true,
  },
]

export const todoListSlice = createSlice({
  name: 'todoList',
  initialState: INIT_STATE,
  reducers: {
    addTodo(state: TodoItemType[], action: PayloadAction<TodoItemType>) {
      return [...state, action.payload]
    },

    removeTodo(state: TodoItemType[], action: PayloadAction<{ id: string }>) {
      return state.filter(item => item.id !== action.payload.id)
    },

    toggleCompleted(state: TodoItemType[], action: PayloadAction<{ id: string }>) {
      return state.map(item => {
        if (item.id === action.payload.id) {
          item.completed = !item.completed
        }
        return item
      })
    },
  },
})

export const { addTodo, removeTodo, toggleCompleted } = todoListSlice.actions

export default todoListSlice.reducer
